package tool

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"main/model"
	"xorm.io/xorm"
)

var DbEngine *OrmEngine

type OrmEngine struct {
	*xorm.Engine
}

func NewOrmEngine(cfg *Config) (*OrmEngine, error) {
	database := cfg.Database
	dataSource := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=%s",
		database.User,
		database.Password,
		database.Host,
		database.Port,
		database.DbName,
		database.Charset,
	)
	log.Printf(dataSource)
	engine, err := xorm.NewEngine(database.Driver, dataSource)
	if err != nil {
		return nil, err
	}
	engine.ShowSQL(database.ShowSql) // 输出sql语句

	err = engine.Sync2(
		new(model.SmsCode),
		new(model.Member),
		new(model.FoodCategory),
		new(model.Shop),
		new(model.Service),
		new(model.ShopService),
		new(model.Goods),
	)
	if err != nil {
		return nil, err
	}

	ormEngine := new(OrmEngine)
	ormEngine.Engine = engine
	DbEngine = ormEngine

	// 初始化数据
	// InitShopData()
	// InitGoodsData()

	return ormEngine, err
}

// InitShopData 插入数据
func InitShopData() {
	shops := []model.Shop{
		model.Shop{
			Name:            "嘉禾一品",
			PromotionInfo:   "欢迎光临,优惠多多!",
			Address:         "新安街道",
			Phone:           "13297963625",
			Status:          1,
			Longitude:       123.25,
			Latitude:        56.56,
			ImagePath:       "",
			IsNew:           true,
			IsPremium:       true,
			Rating:          5,
			RatingCount:     5,
			RecentOrderNum:  20,
			MinimumOrderNum: 5,
			DeliveryFee:     6,
			OpeningHours:    "24 hours",
		},
	}

	// 事务
	session := DbEngine.NewSession()
	defer session.Close()

	if err := session.Begin(); err != nil {
		log.Printf("session begin failed:%v", err)
		return
	}

	for _, shop := range shops {
		if _, err := session.InsertOne(&shop); err != nil {
			session.Rollback()
			return
		}
	}
	if err := session.Commit(); err != nil {
		log.Printf("session commit failed:%v", err)
	}
}

func InitGoodsData() {
	goods := []model.Goods{
		model.Goods{
			Name:        "嘉和一品(温都水城)",
			Description: "嘉和一品描述",
			Icon:        "图标",
			SellCount:   100,
			Price:       23.99,
			OldPrice:    50.32,
			ShopId:      1,
		},
		model.Goods{
			Name:        "杨国福麻辣烫",
			Description: "杨国福麻辣烫描述",
			Icon:        "图标",
			SellCount:   200,
			Price:       28.99,
			OldPrice:    60.32,
			ShopId:      1,
		},
	}

	session := DbEngine.NewSession()
	defer session.Close()

	if err := session.Begin(); err != nil {
		log.Printf("session begin failed:%v", err)
		return
	}

	cnt, err := session.InsertMulti(&goods)
	if err != nil || int(cnt) != len(goods) {
		log.Printf("session insert failed:%v", err)
		session.Rollback()
		return
	}

	if err := session.Commit(); err != nil {
		log.Printf("session commit failed: %v", err)
		return
	}
}

